package leetcode.code0815;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	public int numBusesToDestination(int[][] routes, int source, int target) {
		if (source == target) {
			return 0;
		}
		// 某一站stop，有哪些路线。
		Map<Integer, List<Integer>> stops = new HashMap<>();
		// 是否有source，是否有target
		boolean hasSource = false, hasTarget = false;
		for (int i = 0; i < routes.length; i++) {
			for (int stop : routes[i]) {
				List<Integer> route = stops.getOrDefault(stop, new ArrayList<>());
				route.add(i);
				stops.put(stop, route);
				if (stop == source) {
					hasSource = true;
				} else if (stop == target) {
					hasTarget = true;
				}
			}
		}
		// 有一个没有，歇了，return -1
		if (!hasSource || !hasTarget) {
			return -1;
		}
		// 到达某一个stop的最小乘车次数
		Map<Integer, Integer> minSteps = new HashMap<>();
		Queue<Integer> queue = new LinkedList<>();
		queue.add(source);
		// 到达起点最少0次
		minSteps.put(source, 0);
		while (!queue.isEmpty()) {
			int curStop = queue.poll();
			int nextStep = minSteps.get(curStop) + 1;// 到达下一站，已经乘坐的公交数量
			List<Integer> curRoutes = stops.get(curStop);// 当前车站所有路线上的站点，均可抵达。
			for (int routeIdx : curRoutes) {
				int[] nextStops = routes[routeIdx];
				for (int nextStop : nextStops) {
					if (nextStop == target) {// 到目的地了
						return nextStep;
					}
					if (minSteps.containsKey(nextStop)) {
						// 到过这里，一定没有之前小，不能现在从nextStop这里做出发点了，换句话说，queue里有这站，跳过
						continue;
					}
					queue.add(nextStop);
					minSteps.put(nextStop, nextStep);
				}
			}
		}
		return -1;
	}

	@Override
	public void debug4() {
		HelpDebug.compare(2, this.numBusesToDestination(HelpDebug.str2array1("[[1,2,7],[3,6,7]]"), 1, 6));
		HelpDebug.compare(-1, this.numBusesToDestination(HelpDebug.str2array1("[[7,12],[4,5,15],[6],[15,19],[9,12,13]]"), 15, 12));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
